#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@NAME          : user_dto.py
@TIME          : 2025/03/01 10:00:00
@AUTHOR        : chenlip
@VERSION       : 0.1.0
@DESCRIPTION   : 用户模块数据处理对象，包含对用户体系相关表的CRUD操作
'''

import bcrypt
from typing import Dict, List, Tuple, Union, Optional, Any
from sqlalchemy import desc, asc, and_, or_, not_
from sqlalchemy.exc import SQLAlchemyError

from init_app import sqldb as db
from app.dto.base_dto import BaseDTO

from app.models.user import User, UserLevel, UserExtension, UserMeta, UserActionLog
from app.common.error_codes import ErrorCode

class UserDTO(BaseDTO):
    """用户主表数据处理对象"""

    @staticmethod
    def hash_password(password: str) -> str:
        """
        对密码进行bcrypt哈希处理
        
        Args:
            password: 密码明文
            
        Returns:
            str: bcrypt哈希后的密码
        """
        salt = bcrypt.gensalt(rounds=12)
        hashed = bcrypt.hashpw(password.encode('utf-8'), salt)
        return hashed.decode('utf-8')
    
    @staticmethod
    def check_password(password: str, password_hash: str) -> bool:
        """
        验证密码是否正确
        
        Args:
            password: 密码明文
            password_hash: 密码哈希值
            
        Returns:
            bool: 密码是否正确
        """
        return bcrypt.checkpw(password.encode('utf-8'), password_hash.encode('utf-8'))

    @classmethod
    def create_user(cls, user_data: Dict) -> Dict:
        """
        创建新用户

        Args:
            user_data: 用户数据字典，包含必要字段

        Returns:
            Dict: 包含操作结果和新创建用户ID
        """
        try:
            user = User(
                user_id=user_data.get('user_id'),
                loginname=user_data.get('loginname'),
                nickname=user_data.get('nickname'),
                password_hash=cls.hash_password(user_data.get('password')),
                email=user_data.get('email'),
                phone=user_data.get('phone'),
                avatar=user_data.get('avatar', '/static/avatar/default.png'),
                description=user_data.get('description', ''),
                role=user_data.get('role', 0),
                is_ai_user=user_data.get('is_ai_user', 0),
                status=user_data.get('status', 1),
            )
            
            # 敏感信息AES加密
            if user_data.get('real_name'):
                user.real_name = cls.aes_encrypt(user_data.get('real_name'))
                
            if user_data.get('id_card'):
                user.id_card = cls.aes_encrypt(user_data.get('id_card'))
            
            # 密保问题（如果有）
            if user_data.get('security_question'):
                user.security_question = user_data.get('security_question')
            
            db.session.add(user)
            db.session.flush()
            
            # 创建用户扩展信息
            user_extension = UserExtension(
                user_id=user.user_id,
                current_level=1,
                current_points=10,
                privacy_settings={"show_email": False, "hide_last_login": False}
            )
            db.session.add(user_extension)
            
            db.session.commit()
            
            return {
                "success": True,
                "message": "用户创建成功",
                "user_id": user.user_id
            }
            
        except SQLAlchemyError as e:
            # 回滚
            db.session.rollback()
            return cls.handle_db_error(e)
    
    @classmethod
    def get_user_by_id(cls, user_id: int, with_extension: bool = False) -> Dict:
        """
        通过ID获取用户信息
        
        Args:
            user_id: 用户ID
            with_extension: 是否包含扩展信息
            
        Returns:
            Dict: 用户信息
        """
        try:
            user = db.session.query(User).filter(User.user_id == user_id).first()
            
            if not user:
                return {"success": False, "code": "60005", "message": "用户不存在"}
            
            user_dict = {
                "user_id": user.user_id,
                "nickname": user.nickname,
                "loginname": user.loginname,
                "email": user.email,
                "phone": user.phone,
                "avatar": user.avatar,
                "birthday": user.birthday,
                "qq": user.qq,
                "user_sex": user.user_sex,
                "real_name": user.real_name,
                "id_card": user.id_card,
                "description": user.description,
                "status": user.status,
                "role": user.role,
                "is_ai_user": user.is_ai_user,
                "create_time": user.create_time,
                "update_time": user.update_time,
            }
            
            # 解密敏感信息
            if user.real_name:
                user_dict["real_name"] = cls.aes_decrypt(user.real_name)
            
            if user.id_card:
                user_dict["id_card"] = cls.aes_decrypt(user.id_card)
            
            # 如果需要扩展信息，则添加
            if with_extension and user.extension:
                ext = user.extension
                user_dict["extension"] = {
                    "current_points": ext.current_points,
                    "current_level": ext.current_level,
                    "last_login_time": ext.last_login_time,
                    "total_online": ext.total_online,
                    "privacy_settings": ext.privacy_settings
                }
                
                if ext.level:
                    user_dict["level"] = {
                        "level_id": ext.level.level_id,
                        "level_name": ext.level.level_name,
                        "badge_icon": ext.level.badge_icon
                    }

            # 获取用户元数据
            meta_result = UserMetaDTO.get_by_user_id(user_id)
            if meta_result["success"]:
                user_dict["meta"] = meta_result["data"]
            
            return {"success": True, "data": user_dict}
            
        except SQLAlchemyError as e:
            return cls.handle_db_error(e, rollback=False)
    
    @classmethod
    def get_user_by_loginname(cls, loginname: str) -> Dict:
        """
        通过登录名获取用户信息
        
        Args:
            loginname: 登录名
            
        Returns:
            Dict: 用户信息
        """
        try:
            user = db.session.query(User).filter(User.loginname == loginname).first()
            
            if not user:
                return {"success": False, "code": "60005", "message": "用户不存在"}
            
            return cls.get_user_by_id(user.user_id)
            
        except SQLAlchemyError as e:
            return cls.handle_db_error(e, rollback=False)
    
    @classmethod
    def get_user_by_email(cls, email: str) -> Dict:
        """
        通过邮箱获取用户信息
        
        Args:
            email: 邮箱
            
        Returns:
            Dict: 用户信息
        """
        try:
            user = db.session.query(User).filter(User.email == email).first()
            
            if not user:
                return {"success": False, "code": "60005", "message": "用户不存在"}
            
            return cls.get_user_by_id(user.user_id)
            
        except SQLAlchemyError as e:
            return cls.handle_db_error(e, rollback=False)
    
    @classmethod
    def authenticate_user(cls, login_id: str, password: str) -> Dict:
        """
        用户认证
        
        Args:
            login_id: 登录标识（用户名、邮箱或手机号）
            password: 密码明文
            
        Returns:
            Dict: 认证结果和用户信息
        """
        try:
            user = db.session.query(User).filter(
                or_(
                    User.loginname == login_id,
                    User.email == login_id,
                    User.phone == login_id
                )
            ).first()
            
            if not user:
                return {"success": False, "code":"60005", "message": "用户不存在"}, None
            
            if user.status != 1:
                status_messages = {
                    0: "账户已被封禁",
                    4: "账户已注销"
                }
                return {"success": False, "code":"60008", "message": status_messages.get(user.status, "账户状态异常")}, None
            
            if not cls.check_password(password, user.password_hash):
                return {"success": False, "code":"60004", "message": "密码错误"}, None
            
            result = cls.get_user_by_id(user.user_id, with_extension=True)
            
            return result, user
            
        except SQLAlchemyError as e:
            return cls.handle_db_error(e, rollback=False)
    
    @classmethod
    def update_user(cls, user_id: int, update_data: Dict) -> Dict:
        """
        更新用户信息
        
        Args:
            user_id: 用户ID
            update_data: 更新数据
            
        Returns:
            Dict: 更新结果
        """
        try:
            user = db.session.query(User).filter(User.user_id == user_id).first()
            
            if not user:
                return {"success": False, "code": "60005", "message": "用户不存在"}
                
            # 禁止直接更新的字段
            forbidden_fields = ['user_id', 'loginname', 'password_hash', 'create_time']
            
            # 需要加密的字段
            encrypt_fields = ['real_name', 'id_card']
            
            # 更新字段
            for field, value in update_data.items():
                if field in forbidden_fields:
                    continue
                    
                if field in encrypt_fields and value:
                    value = cls.aes_encrypt(value)
                    
                setattr(user, field, value)
            
            db.session.commit()
            
            return {"success": False, "code": "10000", "message":  "用户信息更新成功"}
            
        except SQLAlchemyError as e:
            return cls.handle_db_error(e)
        
    @classmethod
    def update_avatar(cls, user_id: int, avatar_url: str) -> Dict:
        """
        更新用户头像
        
        Args:
            user_id: 用户ID
            avatar_url: 头像URL
            
        Returns:
            Dict: 更新结果
        """
        try:
            user = db.session.query(User).filter(User.user_id == user_id).first()
            
            if not user:
                return {"success": False, "code": "60005", "message": "用户不存在"}
                
            user.avatar = avatar_url
            db.session.commit()
            
            return {"success": False, "code": "10000", "message":  "用户头像更新成功"}
            
        except SQLAlchemyError as e:
            return cls.handle_db_error(e)
    
    @classmethod
    def change_password(cls, user_id: int, old_password: str, new_password: str) -> Dict:
        """
        修改用户密码
        
        Args:
            user_id: 用户ID
            old_password: 旧密码
            new_password: 新密码
            
        Returns:
            Dict: 修改结果
        """
        try:
            user = db.session.query(User).filter(User.user_id == user_id).first()
            
            if not user:
                return {"success": False, "code": "60005", "message": "用户不存在"}
            
            if not cls.check_password(old_password, user.password_hash):
                return {"success": False, "message": "原密码错误"}
            
            user.password_hash = cls.hash_password(new_password)
            db.session.commit()
            
            return {"success": False, "code": "10000", "message":  "密码修改成功"}
            
        except SQLAlchemyError as e:
            return cls.handle_db_error(e)
    
    @classmethod
    def deactivate_user(cls, user_id: int) -> Dict:
        """
        注销用户账户
        
        Args:
            user_id: 用户ID
            reason: 注销原因
            
        Returns:
            Dict: 注销结果
        """
        try:
            user = db.session.query(User).filter(User.user_id == user_id).first()
            
            if not user:
                return {"success": False, "code": "60005", "message": "用户不存在"}
            
            # 设置为注销状态
            user.status = 4

            # 将用户账户虚拟化，实际账户信息保留，但不再允许登录
            user.loginname = f'D_{user.loginname}'
            # 修改用户登录密码为固定值
            user.password_hash = cls.hash_password('yougrong#888')
            
            db.session.commit()
            
            return {"success": False, "code": "10000", "message":  "用户账户已成功注销"}
            
        except SQLAlchemyError as e:
            return cls.handle_db_error(e)
        
    @classmethod
    def query_users(cls, query_params: Dict) -> Dict:
        """
        查询用户列表
        
        Args:
            query_params: 查询参数，包含状态、角色、注册时间等，例如：
                {
                    "status": 1,
                    "role": 0,
                    "is_ai_user": 0,
                    "start_time": "2025-01-01",
                    "page": 1,
                    "page_size": 20
                }
            
        Returns:
            Dict: 查询结果
        """
        try:
            query = db.session.query(User)
            
            # 状态过滤
            if 'status' in query_params:
                query = query.filter(User.status == query_params['status'])
            
            # 角色过滤
            if 'role' in query_params:
                query = query.filter(User.role == query_params['role'])

            # 是否AI用户过滤
            if 'is_ai_user' in query_params:
                query = query.filter(User.is_ai_user == query_params['is_ai_user'])

            # 注册时间范围过滤
            if 'start_time' in query_params:
                query = query.filter(User.create_time >= query_params['start_time'])
            
            # 分页
            page = query_params.get('page', 1)
            page_size = query_params.get('page_size', 20)
            offset = (page - 1) * page_size
            
            total = query.count()
            users = query.order_by(desc(User.create_time)).offset(offset).limit(page_size).all()
            
            result = []
            for user in users:
                result.append({
                    "user_id": user.user_id,
                    "nickname": user.nickname,
                    "loginname": user.loginname,
                    "email": user.email,
                    "phone": user.phone,
                    "avatar": user.avatar,
                    "real_name": cls.aes_decrypt(user.real_name) if user.real_name else '',
                    "id_card": cls.aes_decrypt(user.id_card) if user.id_card else '',
                    "description": user.description,
                    "status": user.status,
                    "role": user.role,
                    "is_ai_user": user.is_ai_user,
                    "create_time": user.create_time,
                    "update_time": user.update_time,
                })
            
            return {
                "success": True,
                "data": result,
                "total": total
            }
            
        except SQLAlchemyError as e:
            return cls.handle_db_error(e, rollback=False)


class UserLevelDTO(BaseDTO):
    """用户等级数据处理对象"""
    
    @classmethod
    def get_all_levels(cls) -> Dict:
        """
        获取所有用户等级
        
        Returns:
            Dict: 所有用户等级
        """
        try:
            levels = db.session.query(UserLevel).order_by(UserLevel.level_id).all()
            
            levels_list = []
            for level in levels:
                levels_list.append({
                    "level_id": level.level_id,
                    "level_name": level.level_name,
                    "min_points": level.min_points,
                    "privileges": level.privileges,
                    "badge_icon": level.badge_icon,
                    "description": level.description
                })
            
            return {"success": True, "data": levels_list}
            
        except SQLAlchemyError as e:
            return cls.handle_db_error(e, rollback=False)
    
    @classmethod
    def get_level_by_id(cls, level_id: int) -> Dict:
        """
        根据ID获取等级信息
        
        Args:
            level_id: 等级ID
            
        Returns:
            Dict: 等级信息
        """
        try:
            level = db.session.query(UserLevel).filter(UserLevel.level_id == level_id).first()
            
            if not level:
                return {"success": False, "message": "等级不存在"}
            
            level_data = {
                "level_id": level.level_id,
                "level_name": level.level_name,
                "min_points": level.min_points,
                "privileges": level.privileges,
                "badge_icon": level.badge_icon,
                "description": level.description
            }
            
            return {"success": True, "data": level_data}
            
        except SQLAlchemyError as e:
            return cls.handle_db_error(e, rollback=False)
    
    @classmethod
    def get_level_by_points(cls, points: int) -> Dict:
        """
        根据积分获取等级
        
        Args:
            points: 积分
            
        Returns:
            Dict: 等级信息
        """
        try:
            level = db.session.query(UserLevel)\
                .filter(UserLevel.min_points <= points)\
                .order_by(desc(UserLevel.min_points))\
                .first()
            
            if not level:
                level = db.session.query(UserLevel).order_by(asc(UserLevel.level_id)).first()
                
            if not level:
                return {"success": False, "message": "未找到等级信息"}
            
            level_data = {
                "level_id": level.level_id,
                "level_name": level.level_name,
                "min_points": level.min_points,
                "privileges": level.privileges,
                "badge_icon": level.badge_icon,
                "description": level.description
            }
            
            return {"success": True, "data": level_data}
            
        except SQLAlchemyError as e:
            return cls.handle_db_error(e, rollback=False)
    
    @classmethod
    def create_level(cls, level_data: Dict) -> Dict:
        """
        创建等级
        
        Args:
            level_data: 等级数据
            
        Returns:
            Dict: 创建结果
        """
        try:
            level = UserLevel(
                level_name=level_data.get('level_name'),
                min_points=level_data.get('min_points'),
                privileges=level_data.get('privileges', {}),
                badge_icon=level_data.get('badge_icon', ''),
                description=level_data.get('description', '')
            )
            
            db.session.add(level)
            db.session.commit()
            
            return {
                "success": True,
                "message": "等级创建成功",
                "level_id": level.level_id
            }
            
        except SQLAlchemyError as e:
            return cls.handle_db_error(e)
    
    @classmethod
    def update_level(cls, level_id: int, update_data: Dict) -> Dict:
        """
        更新等级信息
        
        Args:
            level_id: 等级ID
            update_data: 更新数据
            
        Returns:
            Dict: 更新结果
        """
        try:
            level = db.session.query(UserLevel).filter(UserLevel.level_id == level_id).first()
            
            if not level:
                return {"success": False, "message": "等级不存在"}
                
            # 更新字段
            for field, value in update_data.items():
                if hasattr(level, field):
                    setattr(level, field, value)
            
            db.session.commit()
            
            return {"success": False, "code": "10000", "message":  "等级信息更新成功"}
            
        except SQLAlchemyError as e:
            db.session.rollback()
            return cls.handle_db_error(e)


class UserExtensionDTO(BaseDTO):
    """用户扩展信息数据处理对象"""
    
    @classmethod
    def get_by_user_id(cls, user_id: int) -> Dict:
        """
        获取用户扩展信息
        
        Args:
            user_id: 用户ID
            
        Returns:
            Dict: 用户扩展信息
        """
        try:
            extension: UserExtension = db.session.query(UserExtension).filter(
                UserExtension.user_id == user_id
            ).first()
            
            if not extension:
                return {"success": False, "message": "未找到用户扩展信息"}
            
            # 获取关联的等级信息
            level = None
            if extension.level:
                level = {
                    "level_id": extension.level.level_id,
                    "level_name": extension.level.level_name,
                    "badge_icon": extension.level.badge_icon
                }
            
            extension_data = {
                "user_id": extension.user_id,
                "privacy_settings": extension.privacy_settings,
                "current_points": extension.current_points,
                "current_level": extension.current_level,
                "last_login_time": extension.last_login_time,
                "total_online": extension.total_online,
                "level": level
            }
            
            return {"success": True, "data": extension_data}
            
        except SQLAlchemyError as e:
            return cls.handle_db_error(e, rollback=False)
    
    @classmethod
    def update_extension(cls, user_id: int, update_data: Dict) -> Dict:
        """
        更新用户扩展信息
        
        Args:
            user_id: 用户ID
            update_data: 更新数据
            
        Returns:
            Dict: 更新结果
        """
        try:
            extension = db.session.query(UserExtension).filter(
                UserExtension.user_id == user_id
            ).first()
            
            if not extension:
                return {"success": False, "message": "未找到用户扩展信息"}
                
            # 更新字段
            for field, value in update_data.items():
                if hasattr(extension, field):
                    setattr(extension, field, value)
            
            db.session.commit()
            
            return {"success": False, "code": "10000", "message":  "用户扩展信息更新成功"}
            
        except SQLAlchemyError as e:
            return cls.handle_db_error(e)
    
    @classmethod
    def update_user_points(cls, user_id: int, points_change: int) -> Dict:
        """
        更新用户积分
        
        Args:
            user_id: 用户ID
            points_change: 积分变化值
            
        Returns:
            Dict: 更新结果
        """
        try:
            extension = db.session.query(UserExtension).filter(
                UserExtension.user_id == user_id
            ).first()
            
            if not extension:
                return {"success": False, "message": "未找到用户扩展信息"}
            
            # 更新积分
            new_points = extension.current_points + points_change
            extension.current_points = max(0, new_points)  # 积分不能为负
            
            # 获取对应等级
            level_result = UserLevelDTO.get_level_by_points(extension.current_points)
            if level_result["success"]:
                level_data = level_result["data"]
                extension.current_level = level_data["level_id"]
            
            db.session.commit()
            
            return {
                "success": True, 
                "message": "用户积分更新成功",
                "current_points": extension.current_points,
                "current_level": extension.current_level
            }
            
        except SQLAlchemyError as e:
            return cls.handle_db_error(e)


class UserMetaDTO(BaseDTO):
    """用户元数据数据处理对象"""
    
    @classmethod
    def get_by_user_id(cls, user_id: int, meta_group: str = None) -> Dict:
        """
        获取用户元数据
        
        Args:
            user_id: 用户ID
            meta_group: 元数据分组
            
        Returns:
            Dict: 用户元数据
        """
        try:
            query = db.session.query(UserMeta).filter(UserMeta.user_id == user_id)
            
            if meta_group:
                query = query.filter(UserMeta.meta_group == meta_group)
            
            meta_list = query.all()
            
            result = {}
            for meta in meta_list:
                if meta.meta_group not in result:
                    result[meta.meta_group] = {}
                    
                result[meta.meta_group][meta.meta_key] = meta.meta_value
            
            return {"success": True, "data": result}
            
        except SQLAlchemyError as e:
            return cls.handle_db_error(e, rollback=False)
    
    @classmethod
    def set_meta_value(cls, user_id: int, meta_group: str, meta_key: str, meta_value: str) -> Dict:
        """
        设置用户元数据
        
        Args:
            user_id: 用户ID
            meta_group: 元数据分组
            meta_key: 元数据键
            meta_value: 元数据值
            
        Returns:
            Dict: 设置结果
        """
        try:
            # 查找是否已存在
            meta = db.session.query(UserMeta).filter(
                and_(
                    UserMeta.user_id == user_id,
                    UserMeta.meta_group == meta_group,
                    UserMeta.meta_key == meta_key
                )
            ).first()
            
            if meta:
                # 更新
                meta.meta_value = meta_value
            else:
                # 创建
                meta = UserMeta(
                    user_id=user_id,
                    meta_group=meta_group,
                    meta_key=meta_key,
                    meta_value=meta_value
                )
                db.session.add(meta)
            
            db.session.commit()
            
            return {"success": False, "code": "10000", "message":  "元数据设置成功"}
            
        except SQLAlchemyError as e:
            return cls.handle_db_error(e)
    
    @classmethod
    def delete_meta(cls, user_id: int, meta_group: str = None, meta_key: str = None) -> Dict:
        """
        删除用户元数据
        
        Args:
            user_id: 用户ID
            meta_group: 元数据分组
            meta_key: 元数据键
            
        Returns:
            Dict: 删除结果
        """
        try:
            query = db.session.query(UserMeta).filter(UserMeta.user_id == user_id)
            
            if meta_group:
                query = query.filter(UserMeta.meta_group == meta_group)
                
            if meta_key:
                query = query.filter(UserMeta.meta_key == meta_key)
            
            count = query.delete()
            
            db.session.commit()
            
            return {
                "success": True, 
                "message": f"成功删除{count}条元数据",
                "count": count
            }
            
        except SQLAlchemyError as e:
            return cls.handle_db_error(e)


class UserActionLogDTO(BaseDTO):
    """用户行为日志数据处理对象"""
    
    @classmethod
    def log_action(cls, user_id: int, action_type: int, target_type: int, 
                  target_id: int, client_info: Dict = None, duration: int = None) -> Dict:
        """
        记录用户行为
        
        Args:
            user_id: 用户ID
            action_type: 行为类型
            target_type: 目标类型
            target_id: 目标ID
            client_info: 客户端信息
            duration: 持续时间
            
        Returns:
            Dict: 记录结果
        """
        try:
            log = UserActionLog(
                user_id=user_id,
                action_type=action_type,
                target_type=target_type,
                target_id=target_id,
                client_info=client_info,
                duration=duration
            )
            
            # 如果有客户端IP，提取到单独字段
            if client_info and 'ip' in client_info:
                log.client_ip = client_info['ip']
            
            db.session.add(log)
            db.session.commit()
            
            return {
                "success": True,
                "message": "行为记录成功",
                "log_id": log.log_id
            }
            
        except SQLAlchemyError as e:
            return cls.handle_db_error(e)
    
    @classmethod
    def get_user_actions(cls, user_id: int, action_type: int = None, 
                        start_time = None, end_time = None, limit: int = 50, desc: bool=True) -> Dict:
        """
        获取用户行为日志
        
        Args:
            user_id: 用户ID
            action_type: 行为类型
            start_time: 开始时间
            end_time: 结束时间
            limit: 限制数量
            desc: 是否降序, 默认True
            
        Returns:
            Dict: 用户行为日志
        """
        try:
            query = db.session.query(UserActionLog).filter(UserActionLog.user_id == user_id)
            
            if action_type is not None:
                query = query.filter(UserActionLog.action_type == action_type)
                
            if start_time:
                query = query.filter(UserActionLog.create_time >= start_time)
                
            if end_time:
                query = query.filter(UserActionLog.create_time <= end_time)
            
            logs = query.order_by(desc(UserActionLog.create_time)).limit(limit).all()
            
            result = []
            for log in logs:
                result.append({
                    "log_id": log.log_id,
                    "user_id": log.user_id,
                    "action_type": log.action_type,
                    "target_type": log.target_type,
                    "target_id": log.target_id,
                    "client_info": log.client_info,
                    "duration": log.duration,
                    "create_time": log.create_time
                })
            
            return {"success": True, "data": result}
            
        except SQLAlchemyError as e:
            return cls.handle_db_error(e, rollback=False)
    
    @classmethod
    def get_target_actions(cls, target_type: int, target_id: int, 
                          action_type: int = None, limit: int = 50) -> Dict:
        """
        获取目标对象的行为日志
        
        Args:
            target_type: 目标类型
            target_id: 目标ID
            action_type: 行为类型
            limit: 限制数量
            
        Returns:
            Dict: 目标对象行为日志
        """
        try:
            query = db.session.query(UserActionLog).filter(
                and_(
                    UserActionLog.target_type == target_type,
                    UserActionLog.target_id == target_id
                )
            )
            
            if action_type is not None:
                query = query.filter(UserActionLog.action_type == action_type)
            
            logs = query.order_by(desc(UserActionLog.create_time)).limit(limit).all()
            
            result = []
            for log in logs:
                result.append({
                    "log_id": log.log_id,
                    "user_id": log.user_id,
                    "action_type": log.action_type,
                    "target_type": log.target_type,
                    "target_id": log.target_id,
                    "client_info": log.client_info,
                    "duration": log.duration,
                    "create_time": log.create_time
                })
            
            return {"success": True, "data": result}
            
        except SQLAlchemyError as e:
            return cls.handle_db_error(e, rollback=False)
        
    @classmethod
    def delete_user_actions(cls, user_id: int, action_type: int = None, 
                           start_time = None, end_time = None) -> Dict:
        """
        删除用户行为日志
        
        Args:
            user_id: 用户ID
            action_type: 行为类型
            start_time: 开始时间
            end_time: 结束时间
            
        Returns:
            Dict: 删除结果
        """
        try:
            query = db.session.query(UserActionLog).filter(UserActionLog.user_id == user_id)
            
            if action_type is not None:
                query = query.filter(UserActionLog.action_type == action_type)
                
            if start_time:
                query = query.filter(UserActionLog.create_time >= start_time)
                
            if end_time:
                query = query.filter(UserActionLog.create_time <= end_time)
            
            count = query.delete()
            db.session.commit()
            
            return {
                "success": True, 
                "message": f"成功删除{count}条用户行为日志",
                "count": count
            }
            
        except SQLAlchemyError as e:
            return cls.handle_db_error(e)
